package com.wedo.star.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wedo.book.pojo.Book;
import com.wedo.common.pojo.PageResult;
import com.wedo.star.client.BookClient;
import com.wedo.star.mapper.StarMapper;
import com.wedo.star.pojo.BookStar;
import com.wedo.star.result.ResultStar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class StarService {

    @Autowired
    private StarMapper starMapper;

    @Autowired
    private BookClient bookClient;

    public PageResult<ResultStar> queryStarPageByUid(Long uid,Long bid, Integer page, Integer rows) {
        if (uid == null) {
            return null;
        }
        Example example = new Example(BookStar.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("uId",uid);
        if (bid != null) {
            criteria.andEqualTo("bId",bid);
        }

        PageHelper.startPage(page, rows);
        List<BookStar> bookStars = this.starMapper.selectByExample(example);

        List<ResultStar> result = bookStars.stream().map(bookStar -> {
            Book book = this.bookClient.queryBookByBid(bookStar.getbId());
            ResultStar resultStar = new ResultStar();
            resultStar.setbId(bookStar.getbId());
            resultStar.setcId(bookStar.getcId());
            resultStar.setuId(bookStar.getuId());
            resultStar.setBook(book);
            return resultStar;
        }).collect(Collectors.toList());


        PageInfo<BookStar> pageInfo = new PageInfo<>(bookStars);

        return new PageResult<>(pageInfo.getTotal(),pageInfo.getPages(),result);
    }

    public BookStar addBookStar(BookStar bookStar) {
        if (bookStar.getuId() == null||bookStar.getbId() == null || bookStar.getcId() == null) {
            return null;
        }
        this.starMapper.insertSelective(bookStar);
        return bookStar;
    }

    public BookStar updateBookStar(BookStar bookStar) {
        if (bookStar.getuId() == null||bookStar.getbId() == null || bookStar.getcId() == null) {
            return null;
        }
        this.starMapper.updateByPrimaryKey(bookStar);
        return bookStar;
    }

    public BookStar deleteBookStar(BookStar bookStar) {
        if (bookStar.getuId() == null || bookStar.getbId() == null) {
            return null;
        }
        this.starMapper.delete(bookStar);
        return bookStar;
    }
}
